/********web.app.js *****/
//全局变量
var appName = {};
base_url = typeof(base_url) != 'undefined' ? base_url : "";
if (typeof(webName) != "undefined") {
    appName[webName] = webName;
}
var ajaxParam = {
    appName: typeof(webName) != 'undefined' ? webName : '',
    view_type: typeof(view_type) != 'undefined' ? view_type : 'Web'
};
var app_init_data = get_param(ajaxParam); /*初始数据*/
if (app_init_data.params) {
    var app_params = app_init_data.params;
    app_params.onBeforeShow = function(param) {
        hiApp.showIndicator();
    };
    app_params.onAfterShow = function(param) {
        hiApp.hideIndicator();
    };
} else {
    var app_params = { params: {} };
}
console.log(app_params);
//全局参数
if (typeof(app_params.urlArgs) != "object") {
    app_params.urlArgs = ajaxParam;
}
//类开始
(function() {
    window.m = function(params) {
        // App
        var app = this;
        var hasinit = 0;
        app.params = {
            swipeBackPage: false,
            cache: true,
            hashchange: 0,
            view_type: 'Web',
            swiper: {},
            cacheIgnore: [],
            cacheIgnoreGetParameters: false,
            cacheDuration: 1000 * 60 * 10,
            // Ten minutes
            ajaxLinks: true,
            animation: false,
            animation_to: '',
            NoAjaxLinks: "back",
            pushStateSeparator: '#',
            NoLinks: ['modal'],
            disableSelect: false,
            history_href: 0,
            base_url: "",
            hashchange: 0,
            debug: false,
            int_url: "",
            urlArgs: {},
            v: '',
            cache_v: '0',
            localStorageExp: 0,
            localStorage: false,

        };
        app.firstInit = 1;
        app.controller = CM;
        app.template = template;
        app.variable = {};
        app.urlCache = {};
        app.view = {
            params: {
                dynamicNavbar: false,
                domCache: false,
                linksView: undefined,
                reloadPages: false
            }

        };
        params = typeof(params) == "object" ? params : {};
        for (var param in params) {
            app.params[param] = params[param];
        }

        /*=======================================
         ************   Plugins API   ************
         =======================================*/
        var _plugins = [];
        app.initPlugins = function() {
            // Initialize plugins
            for (var plugin in app.plugins) {
                var p = app.plugins[plugin](app, app.params[plugin]);
                if (p) _plugins.push(p);
            }
        };
        // Plugin Hooks
        app.pluginHook = function(hook) {
            for (var i = 0; i < _plugins.length; i++) {
                if (_plugins[i].hooks && hook in _plugins[i].hooks) {
                    _plugins[i].hooks[hook](arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]);
                }
            }
        };

        //cache缓存版本号
        app.cache_v = function() {
            if (app.params.debug == true) {
                var v = (new Date()).getTime();
            } else {
                var v = app.params.BoxVersion;
            }
            //console.log(v);
            return v;
        };
        /*==================================================
         Devices
         ====================================================*/
        device: (function() {
                var ua = navigator.userAgent;
                var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
                var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
                var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
                var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
                return {
                    ios: ipad || iphone || ipod,
                    android: android
                };
            })(),
            /*======================================================
             ************   XHR   ************
             ======================================================*/
            // XHR Caching缓存
            app.cache = [];
        app.removeFromCache = function(url) {
            var index = false;
            url = base64_encode(url);
            for (var i = 0; i < app.cache.length; i++) {
                if (app.cache[i].url === url) {
                    index = i;
                }
            }
            if (index !== false) {
                app.cache.splice(index, 1);
            }
        };
        app.addVisCache = function(data) {
            var kk = 1;
            $.each(app.cache, function(i, v) {
                if (v.url == data.url) {
                    app.cache[i] = data;
                    kk = 0;
                    return false;
                }
            });
            if (kk == 1) {
                app.cache.push(data);
            }
        };

        app.getVisCache = function(key) {
            var kk = 1;
            var data = {};
            $.each(app.cache, function(i, v) {
                if (v['url'] == key) {
                    kk = 0;
                    data = app.cache[i];
                }
            });
            if (kk == 1) {
                return false;
            } else {
                return data;
            }
        };


        // XHR
        app.xhr = false;
        app.get = function(url, callback, ignoreCache, view) {
            var _url = url;
            app.xhr = $.ajax({
                url: url,
                method: 'GET',
                //async: true,
                data: app.params.urlArgs,
                beforeSend: app.params.onAjaxStart,
                complete: function(xhr) {
                    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) {
                        app.hideIndicator();
                        var respose = xhr.responseText;
                        if (respose.indexOf('obj-') === 0) {
                            var data = respose.slice(4);
                            //  alert(data);
                            var obj = JSON.parse(data);
                            if (obj.msg) {
                                dialog(obj.msg);
                            }
                            content = obj.content;
                            if (typeof(content) == "string" && content != "") {
                                if (content.indexOf("http") == 0) {
                                    app.jump(content);
                                } else {
                                    app.modal(content);
                                }

                            }
                            if (app.params.onAjaxComplete) {
                                app.params.onAjaxComplete(xhr);
                            }
                            return;
                        }
                        //返回的是脚本
                        if (typeof(respose) == "string" && respose.indexOf('<script') === 0 && respose != "") {
                            $("body").append(respose);
                            return false;
                        }
                        var url_key = base64_encode(_url);
                        var cache_data = {
                            url: url_key,
                            content: xhr.responseText,
                        };
                        if (app.params.cache) {
                            app.addVisCache(cache_data);
                        }

                        console.log(app.params.localStorage);
                        if (app.params.localStorage) {
                            var key = base64_encode(_url);
                            console.log(_url + "页面被缓存了" + key);
                            F(key, cache_data.content, app.params.localStorageExp);
                        }
                        callback(xhr.responseText, false);
                    } else {
                        app.alert('请求发生错误：' + xhr.status);
                        callback(xhr.responseText, true);
                    }
                    if (app.params.onAjaxComplete) app.params.onAjaxComplete(xhr);
                },
                error: function(xhr) {
                    app.alert('请求发生错误：' + xhr.status);
                    //alert(xhr.responseText);
                    app.hideIndicator();
                    callback(xhr.responseText, true);
                    if (app.params.onAjaxError) {
                        app.params.onAjaxError(xhr);
                    }
                }
            });

            if (view) {
                view.xhr = app.xhr;
            }
            // return app.xhr;
        };


        /*======================================================
         ************   Navigation / Router   ************
         ======================================================*/
        app.router = {
            // Temporary DOM Element
            temporaryDom: document.createElement('div'),

            preprocess: function(view, content, url, next) {
                // Plugin hook
                app.pluginHook('routerPreprocess', view, content, url, next);

                // Preprocess by plugin
                content = app.pluginProcess('preprocess', content);

                if (view && view.params && view.params.preprocess) {
                    content = view.params.preprocess(content, url, next);
                    if (typeof content !== 'undefined') {
                        next(content);
                    }
                } else if (app.params.preprocess) {
                    content = app.params.preprocess(content, url, next);
                    if (typeof content !== 'undefined') {
                        next(content);
                    }
                } else {
                    next(content);
                }
            },
            preroute: function(view, options) {
                app.pluginHook('routerPreroute', view, options);
            },


        };
        /*******本地缓存数据*localStorage**/
        app.S = function(key, value) {
            return S(key, value);
        };

        app.router.load_name = function(name) {
            var page = $("[data-page='" + name + "']");
            if ($(page).length > 0) {
                var url = $(page).attr("url");
                var param = app.getUrl(url);
                app.router.load(app.view, param);
            }
        };

        app.router.load_url = function(url) {
            if (url.indexOf("http") == -1) {
                url = base_url + url;
            }
            var param = app.getUrl(url);
            app.router.load(app.view, param);
        };
        //跳转
        app.jump = function(url) {
            if (app.params.ajaxLinks) {
                app.router.load_url(url);
            } else {
                window.location.href = url;
            }
        };



        /*********XHR over*********/
        app.router.load = function(view, options) {
            app.params.hashchange = 1;
            if (app.params.onBeforeShow) {
                app.params.onBeforeShow();
            }
            app.beforeRouterLoad(options);

            options = options || {};
            var url = options.url;
            var content = options.content;
            var pageName = options.pageName;
            if (pageName) {
                if (pageName.indexOf('?') > 0) {
                    options.query = $.parseUrlQuery(pageName);
                    options.pageName = pageName = pageName.split('?')[0];
                }
            }

            var template = options.template;

            function proceed(content) {
                options.content = content;
                app.router._load(view, options);
            }

            view.allowPageChange = false;
            //if (app.xhr && view.xhr && view.xhr === app.xhr) {
            //              app.xhr.abort();
            //              app.xhr = false;
            //          }
            // alert(pageName);
            if (content || pageName) {
                proceed(content);
                return;
            } else if (template) {
                app.router._load(view, options);
                return;
            }

            if (!options.url || options.url === '#') {
                view.allowPageChange = true;
                app.alert("url is miss");
                app.hideIndicator();
                return;
            }
            /********有浏览过有缓存***/
            var _url = url;
            var kk = 1;
            var url_key = base64_encode(url);
            // console.log(app.cache);
            if (app.params.cache) {
                $.each(app.cache, function(i, v) {
                    if (url_key == v.url) {
                        //  console.log('有浏览过有缓存');
                        proceed(v.content);
                        kk = 0;
                        return false;
                    }
                });
            }

            /*******使用缓存***/
            if (kk == 1) {
                //  console.log(url_key);
                Fget(url_key, function(data) {
                    //  console.log("12");
                    //console.log(data);
                    var cache_data = {
                        url: url_key,
                        content: data,
                    };
                    app.addVisCache(cache_data);
                    proceed(data);
                }, function() {
                    run_get();
                })
            }

            function run_get() {
                app.get(options.url, function(content, error) {
                    if (error) {
                        view.allowPageChange = true;
                        return;
                    }
                    proceed(content);
                }, options.ignoreCache, view);
            }
        };

        /*****处理内容**/
        app.router._load = function(view, options) {
            var html = "<div>" + options.content + "</div>";
            var page_content = $(html).find(".page").clone();
            var navbar = $(html).find(".navbar").html();
            options.name = $(html).find(".page").attr("data-page");
            //options.title=$(html).find("title").text();
            //alert(options.name );
            //alert(options.title);
            if (typeof(options.name) == "undefined") {
                if (options.content) {
                    console.log(options.content);
                    app.modal(options.content);
                }
                app.hideIndicator();
                // app.alert("options.name is miss");
                return false;
            }
            // $(".views .view-main").find(".page").removeClass("page-on-center").addClass("cached");
            rightPage = $("[data-page='" + options.name + "']");
            if ($(".page-on-center").length > 0) {
                leftPage = $(".page-on-center");
            } else {
                leftPage = $(".page").eq(0);
            }
            //console.log("leftPage:"+$(leftPage).attr("class"));
            var url = rightPage.attr("url");
            // console.log(app.params.animation_to);
            if (rightPage.length > 0 && url != options.url) {
                rightPage.remove();
                var new_rightPage = app.contentAppend(page_content, options);
                app.animatePages(leftPage, new_rightPage, app.params.animation_to, options);
            } else if (rightPage.length > 0 && url == options.url) { //点后退
                app.animatePages(leftPage, rightPage, app.params.animation_to, options);
            } else {
                rightPage = app.contentAppend(page_content, options);
                app.animatePages(leftPage, rightPage, app.params.animation_to, options);
            }

            if (app.params.onAfterShow) {
                options['old_page_name'] = leftPage.attr("data-page");
                $(document).trigger('pageAfterShow', [options]);
                app.params.onAfterShow(options);
                app.params.hashchange = 0;
                $(".pages .cached").removeAttr("data-app");
                $(".pages .cached").removeAttr("data-afterShow");
                //console.log('showpage');
                // $("[name='app_params_hashchange']").val("0");
                //alert("hashchange:"+app.params.hashchange );
            }
        };

        app.active_toolbar = function(i) {
            $(".toolbar-inner .tab-link ").removeClass("active");
            $(".toolbar-inner").find("[name='" + i + "']").addClass("active");
        };
        app.contentAppend = function(page_content, options) {
            app.beforeAppend(options);
            $(page_content).addClass("cached");
            $(page_content).attr("url", options.url);
            $(".views .pages").append(page_content);
            app.afterAppend(options);
            var rightPage = $("[data-page='" + options.name + "']");
            return rightPage;
        };
        app.beforeRouterLoad = function(options) {
            $(".modal").modal("hide");
        };
        app.beforeAppend = function(options) {

        };
        app.afterAppend = function(options) {
            //console.log("afterAppend");
            $(document).trigger('pageBeforeInit', [options]);
            app.bind($("[data-page='" + options.name + "']"));
        };
        /*********/
        app.animatePages = function(leftPage, rightPage, direction, options) {
            //console.log("direction");
            //console.log(direction);
            // alert(123);
            // $(".pages .page").each(function(i,_this){

            //   })

            $(".pages .page").addClass("cached");
            var removeClasses = 'cached page-on-center page-on-right page-on-left';
            leftPage.removeClass(removeClasses);
            rightPage.removeClass(removeClasses);
            /*隐藏*/
            if (leftPage.length > 0) {
                // alert($(leftPage).attr('data-page'));
                var o = {
                    'url': $(leftPage).attr('url'),
                    'name': $(leftPage).attr('data-page'),
                    'query': getQuery($(leftPage).attr('url'))
                };
                // console.log(o);
                $(document).trigger('pageAfterHide', o);
            }

            if (!direction || !app.params.animation) {
                //console.log("animation_to_nonono"+direction);
                leftPage.addClass("cached");
                rightPage.removeClass("cached").addClass("page-on-center");
                $(document).trigger('pageAfterShow', [options]);
                return false;
            }
            // Loading new page
            if (direction === 'to-left') {
                //console.log($(rightPage).attr("class"));
                leftPage.removeClass(removeClasses).addClass('page-from-center-to-left');
                rightPage.removeClass(removeClasses).addClass('page-from-right-to-center');
                //console.log($(rightPage).attr("class"));
            }
            // Go back
            if (direction === 'to-right') {
                rightPage.removeClass(removeClasses).addClass('page-from-left-to-center');
                leftPage.removeClass(removeClasses).addClass('page-from-center-to-right');

            }




            rightPage.animationEnd(function(e) {
                app.afterAnimation(rightPage, leftPage);
            });
            //app.afterAnimation(rightPage,leftPage);
        };


        app.afterAnimation = function(newPage, oldPage) {
                var removeClasses = 'page-from-center-to-left page-from-right-to-center page-from-left-to-center page-from-center-to-right page-on-right page-on-left page-on-center';
                $(".page").removeClass(removeClasses);
                $(".page").addClass("cached");
                newPage.removeClass("cached");
                newPage.addClass("page-on-center");
                app.params.animation_to = 0;
            },

            /********加载中******/
            app.showIndicator = function() {
                if ($("#pos-center-loader").length == 0) {
                    $('body').prepend('<div class="pos-center" id="pos-center-loader"></div>');
                }
                $(".pos-center").show();
            },
            app.hideIndicator = function() {
                $('.pos-center').remove();
            },

            app.bingAchageUrl = function(pagename) {
                //console.log(123);
                //console.log($(pagename).attr('class'));
                //console.log($(pagename).find("a").length);
                var a = $(pagename).find("a");
                $.each(a, function(i, _this) {
                    var bind = 1;
                    var class_name = $(_this).attr("class");
                    var data_type = $(_this).attr("data-type");
                    //console.log($(_this).attr('href'));
                    if (data_type && data_type != "none" && data_type != "login") {
                        //alert(data_type);
                        bind = 0;
                    }
                    app.params.localStorage = false; //是否缓存在地
                    app.params.localStorageExp = 0; //过期时间
                    app.params.cur_tabbar = -1;
                    var href = $(_this).attr("href");

                    if ($.inArray(data_type, app.params.NoLinks) > -1) {
                        bind = 0;
                    }
                    if ($.inArray(class_name, app.params.NoAjaxLinks) != -1) {
                        bind = 0;
                    }
                    if (href == "" || typeof(href) == "undefined") {
                        bind = 0;
                    }
                    if (typeof(href) == "string") {
                        if (href.indexOf("#") > -1) bind = 0;
                        if (href.indexOf("/") == -1) bind = 0;
                    }
                    if (bind == 1) {
                        $(_this).unbind(app.device.click).bind(app.device.click, function() {
                            app.bindAClick(this);
                            return false;
                        })

                    }
                });

            },
            //链接，使用ajax 请求
            app.bindAClick = function(_this) {
                if ($(_this).attr('data-type') == "login") {
                    //alert(app.login());
                    if (!app.login()) {
                        return false;
                    }
                }
                app.params.hashchange = 0;
                var href = $(_this).attr("href");
                $(_this).focus();
                /****缓存在本地**/
                if ($(_this).attr("localStorage")) {
                    app.params.localStorage = true;
                    app.params.localStorageExp = $(_this).attr("localStorageExp");
                }
                /***不能后退的页面*/

                if (app.params.history_href != 0 && app.params.history_href != href) {
                    var get_html_url = app.params.base_url + "#" + href;
                    var param = app.getUrl(get_html_url);
                    app.router.load(app.view, param);
                    app.params.history_href = 0;
                } else if ($(_this).attr("history") == 0) {
                    // console.log("NoHistory" );
                    var get_html_url = app.params.base_url + "#" + href;
                    var param = app.getUrl(get_html_url);
                    //console.log(param);
                    app.router.load(app.view, param);
                    // app.params.history_href = href;

                } else {
                    /*****跳转了****/
                    //window.location.href=base_url+"#"+href;
                    //console.log("当前地址："+window.location.href);

                    //console.log("跳转了");
                    window.location.href = "#" + href;
                    param = app.getUrl(app.params.base_url + "#" + href);
                    //console.log("当前地址："+window.location.href);
                    //console.log("get_html_url:"+app.params.base_url+"#"+href);
                    var cur_url = $(".page-on-center").attr("url");
                    if (cur_url != param['url']) {
                        //console.log(param);
                        app.params.hashchange = 1;
                        app.router.load(app.view, param);

                    } else {
                        app.router.load(app.view, param);
                    }

                    app.params.history_href = 0;
                }

                app.params.animation_to = "to-left"; //动画效果
                return false;

            },
            /*********显示之后绑定事件*****/
            app.bindAfterShow = function(pagename) {
                if (pagename == "") {
                    pagename = $("body");
                }
                if (!app.device.pc) { //移动端
                    app.loadCss(app.params.res_url + "Js/plug/jquery.plug/Swiper-3.3.1/css/swiper.css");
                    app.getScript(app.params.res_url + "Js/plug/jquery.plug/Swiper-3.3.1/js/swiper.js", function() {
                        $(pagename).find('[data-type="swiperPage"]').each(function(i, _this) { //滑动标签页
                            var id = $(_this).attr("id") ? "#" + $(_this).attr("id") : "." + $(_this).attr("class");
                            if ($(_this).attr("init") != 1) {
                                app.swiperPage(id);
                            }
                            $(_this).attr("init", "1");

                        });
                    })
                }

            },
            /*********hmtl绑定事件*****/
            app.bind = function(pagename) {
                //console.log(pagename);
                if (pagename == "") {
                    pagename = $("body");
                    $("body").bind(app.device.click, function() {
                        $("body").find(".popover").remove();
                    });
                }
                //alert($(pagename).html());

                $('[data-type="modal"]').unbind(app.device.click).bind(app.device.click, function() {
                    app.modal(this);
                    return false;
                });
                $(pagename).find('[target="modal"]').each(function(i, _this) {
                    $(_this).attr("data-type", "modal");
                });


                //图片浏览
                if ($(pagename).find('[data-type="photoBrowser"]').length > 0) {
                    app.loadCss(app.params.res_url + "Js/plug/jquery.plug/swipebox/swipebox.css");
                    app.getScript(app.params.res_url + "Js/plug/jquery.plug/swipebox/jquery.swipebox.js", function() {
                        $(pagename).find('[data-type="photoBrowser"]').each(function(i, _this) {
                            // console.log();
                            $(_this).bind(app.device.click, function() {
                                app.photoBrowser(this);
                                return false;
                            })
                        });
                    })
                }



                $(pagename).find(".back").unbind(app.device.click).bind(app.device.click, function() {
                    if ($(this).parents(".modal").length > 0) {
                        $(this).parents(".modal").modal("hide");
                    } else {
                        history.back();
                        app.params.animation_to = "to-right"; //动画效果
                    }
                });

                $("a").bind(app.device.click, function() {
                    $(this).focus();
                });

                $("select").bind("", function() {
                    $(this).focus();
                });


                $('[data-type="modal"]').unbind(app.device.click).bind(app.device.click, function() {
                    app.modal(this);
                    return false;
                });


                $("[content-a-type='modal']").find("a").unbind(app.device.click).bind(app.device.click, function() {
                    app.modal(this);
                    return false;
                });


                //分类 
                if ($(pagename).find('[data-type="cateList"]').length > 0) {
                    // alert(1);
                    //  console.log(app.params);
                    app.getScript(app.params.res_url + "Js/plug/select.js", function() {
                        $(pagename).find('[data-type="cateList"]').each(function(i, _this) {
                            app.cateList(_this);
                        });
                    })
                }


                //ajax subimit
                if ($(pagename).find('[data-type="ajaxSubmit"]').length > 0) {
                    // alert(1);
                    //  console.log(app.params);
                    app.getScript(app.params.res_url + "Js/plug/jquery.form.js", function() {
                        $(pagename).find('[data-type="ajaxSubmit"]').unbind("submit").bind("submit", function() {
                            app.ajaxSubmit(this);
                            return false;
                        });
                    })
                }
                //弹出
                $('[data-type="popup"]').unbind(app.device.click).bind(app.device.click, function() {
                    var url = $(this).attr("url");
                    app.popup(url, $(this).attr("data-id"), $(this).attr('h'));
                    return false;
                });


                /********确认框***/
                $('[data-type="confirm"]').unbind(app.device.click).bind(app.device.click, function() {
                    app.confirm(this);
                    return false;
                });
                $(".popover_button").unbind(app.device.click).bind(app.device.click, function() {
                    app.popover(this);
                    return false;
                });


                $(".combox").unbind("change").bind("change", function() {
                    app.combox(this);
                    return false;
                });
                $('[data-type="ajaxGet"]').unbind(app.device.click).bind(app.device.click, function() {
                    app.ajaxGet(this);
                    return false;

                });

                $('[data-type="circle"]').each(function(i, _this) {
                    app.circle(_this);
                });


                if (app.device.pc) { //pc端要绑定的
                    $('[data-type="login"]').bind(app.device.click, function() {
                        return app.login($(this).attr('title'));
                    });
                    //时间控
                    if ($(pagename).find(".datetimepicker").length > 0) {
                        // alert($(pagename).find(".datetimepicker").length);
                        app.loadCss(app.params.res_url + "Js/plug/Bootstrap/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css");
                        app.loadCss(app.params.res_url + "Js/plug/Bootstrap/bootstrap-datetimepicker/css/datetimepicker.css");
                        app.getScript(app.params.res_url + "Js/plug/Bootstrap/bootstrap-datetimepicker/js/bootstrap-datetimepicker.js", function() {
                            app.getScript(app.params.res_url + "Js/plug/Bootstrap/bootstrap-datetimepicker/js/bootstrap-datetimepicker.zh-CN.js", function() {
                                $(pagename).find(".datetimepicker").each(function(i, _this) {
                                    app.datetimepicker(_this);
                                })
                            });
                        })

                    }
                    //编辑器
                    // if ($(pagename).find('[data-type="kindeditor"]').length > 0) {
                    //     app.getScript(app.params.res_url + "Js/plug/kindeditor-4.1.10/kindeditor-min.js", function() {
                    //         $(pagename).find('[data-type="kindeditor"]').each(function(i, _this) {
                    //             if ($(_this).attr("init") != 1) {
                    //                 app.kindeditor(_this);
                    //             }
                    //             $(_this).attr("init", "1");
                    //         })
                    //     });
                    // }

                     if ($(pagename).find('[data-type="kindeditor"]').length > 0) {
                         app.loadCss(app.params.res_url + "Js/plug/wangEditor/css/wangEditor.min.css");
                         app.getScript(app.params.res_url + "Js/plug/wangEditor/js/wangEditor.min.js", function() {
                            $(pagename).find('[data-type="kindeditor"]').each(function(i, _this) {
                                if ($(_this).attr("init") != 1) {
                                    app.kindeditor(_this);
                                }
                                $(_this).attr("init", "1");
                            })
                        });
                    }


                    $(".popover_hover").unbind("mouseover").bind("mouseover", function() {
                        app.popover(this);
                        return false;
                    });
                    $('[data-type="copy"]').each(function(i, _this) {
                        return app.copy(_this);
                    });
                }


                if (app.params.ajaxLinks) {
                    app.bingAchageUrl(pagename);
                }
                app.ajaxContent($(pagename).find(".ajaxContent"));
                if (!app.device.pc) {
                    // <!--移动端点击-->
                    // app.getScript(app.params.res_url + "/Js/plug/fastclick.js", function() {
                    FastClick.attach(document.body);
                    // })
                }
                //轮播图
                if ($(pagename).find('[data-type="swiper"]').length > 0) {
                    app.loadCss(app.params.res_url + "Js/plug/jquery.plug/Swiper-3.3.1/css/swiper.css");
                    app.getScript(app.params.res_url + "Js/plug/jquery.plug/Swiper-3.3.1/js/swiper.js", function() {
                        $(pagename).find('[data-type="swiper"]').each(function(i, _this) {
                            var id = $(_this).attr('id');
                            app.swiper(id);
                        });
                    })
                }
                //表单验证<script src="http://res.kaoshituji.com/Js/Bootstrap/validate/0.5.3/bootstrapValidator.min.js"></script>
                //<script src="http://res.kaoshituji.com/Js/Bootstrap/validate/0.5.3/language/zh_CN.js"></script>
                if ($(pagename).find('[data-type="validate"]').length > 0) {
                    app.getScript(app.params.res_url + "Js/plug/Bootstrap/validate/0.5.3/bootstrapValidator.min.js", function() {
                        app.getScript(app.params.res_url + "Js/plug/Bootstrap/validate/0.5.3/language/zh_CN.js", function() {
                            $(document).trigger("validateReady");
                        });
                    });
                }
                /***图片显示**/
                $(pagename).find("img").each(function(i, _this) {
                    var src = $(_this).attr("src");
                    if ($(_this).attr("data-bind") != 1) {
                        $(_this).attr("src", "/Public/Images/0.jpg");
                        $(_this).attr("data-src", src);
                        $(_this).attr("data-bind", 1);
                    }
                });

                $(pagename).find("img").error(function() {
                    $(this).attr("src", "/Public/Images/0.jpg");
                });

                $(function() {
                    /***图片显示**/
                    $("img").each(function(i, _this) {
                        var src = $(_this).attr("data-src");
                        if ($(_this).attr('src') == "/Public/Images/0.jpg") {
                            $(_this).attr("src", src);
                        }
                        //$(_this).attr("data-src",src);
                    });
                });
                //js css 美化显示
                if ($(pagename).find('[data-type="prettify"]').length > 0) {
                    app.loadCss(app.params.res_url + "Js/plug/jquery.plug/prettify/prettify.css");
                    app.getScript(app.params.res_url + "Js/plug/jquery.plug/prettify/prettify.js", function() {
                        prettyPrint();
                    });
                }
                //图片上传
                if ($(pagename).find('[data-type="upload"]').length > 0) {
                    app.loadCss(app.params.res_url + "Js/plug/photo/photo.css");
                    // alert(app.params.res_url + "Js/plug/photo/photo.js");
                    app.getScript(app.params.res_url + "Js/plug/photo/photo.js", function() {
                        //  alert($(pagename).find('[data-type="upload"]').length);
                        $(pagename).find('[data-type="upload"]').each(function(i, _this) {
                            app.upload(_this);
                        })
                    });
                }


            },
            //实例化分类
            app.cateList = function(_this) {
                var type = $(_this).attr("type");
                var cate_id = $(_this).attr("cate_id");
                app.getScript(app.params.res_url + "Js/plug/select.js", function() {
                    $(_this).cateList({ type: type, cate_id: cate_id });
                })
            },
            //上nwfy图片
            app.upload = function(_this) {
                app.loadCss(app.params.res_url + "Js/plug/photo/photo.css");
                app.getScript(app.params.res_url + "Js/plug/photo/photo.js", function() {
                    photo.initUpload($(_this));
                });
            },
            //js css 美化显示 
            app.prettify = function() {
                app.loadCss(app.params.res_url + "Js/plug/jquery.plug/prettify/prettify.css");
                app.getScript(app.params.res_url + "Js/plug/jquery.plug/prettify/prettify.js", function() {
                    prettyPrint();
                })
            },
            //轮播图
            app.swiper = function(id) {
                app.loadCss(app.params.res_url + "Js/plug/jquery.plug/Swiper-3.3.1/css/swiper.css");
                app.getScript(app.params.res_url + "Js/plug/jquery.plug/Swiper-3.3.1/js/swiper.js", function() {
                    swiper = new Swiper('#' + id, {
                        pagination: '#' + id + ' .swiper-pagination',
                        //nextButton: '#swiper_<{$data.name}> .swiper-button-next',
                        //prevButton: '#swiper_<{$data.name}> .swiper-button-prev',
                        loop: true,
                        spaceBetween: 30,
                        centeredSlides: true,
                        autoplay: 2500,
                    })
                })
            },
            //复制
            app.copy = function(_this) {
                app.getScript(app.params.res_url + "Js/plug/jquery.plug/zclip/jquery.zclip.min.js", function() {
                    $(_this).zclip({
                        'path': app.params.res_url + 'Js/plug/jquery.plug/zclip/ZeroClipboard.swf',
                        'afterCopy': function() {
                            dialog('复制成功');
                        },
                        'copy': function() {
                            //  alert(self.closest('code').data('think-source'));
                            var id = ($(this).attr('data-clipboard-target'));
                            return $("#" + id).val();
                        }
                    });
                })
            },
            //时间插件
            app.datetimepicker = function(_this) {
                app.loadCss(app.params.res_url + "Js/plug/Bootstrap/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css");
                app.loadCss(app.params.res_url + "Js/plug/Bootstrap/bootstrap-datetimepicker/css/datetimepicker.css");
                app.getScript(app.params.res_url + "Js/plug/Bootstrap/bootstrap-datetimepicker/js/bootstrap-datetimepicker.js", function() {
                    app.getScript(app.params.res_url + "Js/plug/Bootstrap/bootstrap-datetimepicker/js/bootstrap-datetimepicker.zh-CN.js", function() {
                        $(_this).datetimepicker({
                            "language": 'zh-CN',
                            "autoclose": 1,
                            "minView": $(_this).attr('data-minview') ? $(_this).attr('data-minview') : 2
                        });
                    })
                })
            },

            /**********图片浏览开始呀***/
            app.photoBrowser = function(_this) {
                app.loadCss(app.params.res_url + "Js/plug/jquery.plug/swipebox/swipebox.css");
                app.getScript(app.params.res_url + "Js/plug/jquery.plug/swipebox/jquery.swipebox.js", function() {
                    var url = [];
                    var index = $(_this).attr('index');
                    var cur_img = $(_this).attr('src');
                    //alert(cur_img);
                    var images = $(_this).parents(".photoBrowser").find('img');
                    for (i = 0; i < images.length; i++) {
                        var img = {};
                        var src = images.eq(i).attr('src');
                        var img_data = images.eq(i).attr('data');
                        if (typeof(img_data) != "string") {
                            img_data = src;
                        }
                        var img_title = images.eq(i).attr('alt');
                        if (typeof(img_title) == "string") {
                            img_title = "";
                        }
                        img['title'] = img_title;
                        img['href'] = img_data;
                        url[i] = img;
                        if (cur_img == src) {
                            index = i;
                        }
                    }
                    if (!(index > 0)) {
                        index = 0;
                    }

                    var options = {
                        initialIndexOnArray: index,
                    };
                    $.swipebox(url, options);
                })
            },
            /*********图片浏览到这里结束***/

            app.loadCss = function(url) {
                var css_id = base64_encode(url);
                if (!app.urlCache[css_id]) {
                    app.urlCache[css_id] = css_id;
                    $('head').append('<link href="' + url + '" id="css_id_' + css_id + '" rel="stylesheet" type="text/css" />');
                }
            },

            app.getScript = function(url, func) {
                //console.log(url);
                var script_id = base64_encode(url);
                if (!app.urlCache[script_id]) {
                    $.ajax({
                        url: url,
                        type: "GET",
                        success: function() {
                            app.urlCache[script_id] = script_id;
                            func();
                        },
                        dataType: "script",
                        cache: true,
                    });

                } else {
                    func();
                }
            },

            //编辑器

            app.kindeditor=function(_this){
                app.loadCss(app.params.res_url + "Js/plug/wangEditor/css/wangEditor.min.css");
                app.getScript(app.params.res_url + "Js/plug/wangEditor/js/wangEditor.min.js", function() {
                        var editor = new wangEditor(_this);
                        if (view_type == "AdminWeb") {

                        }else{
                            editor.config.menus = [
                            'bold',
                            'forecolor',
                            'undo',
                            'fontsize',
                            'redo',
                            'fullscreen',
                            'img',
                            'video',
                             'alignleft',
                            'aligncenter',
                            'alignright',
                         ];
                        }
                         editor.config.menuFixed = false;
                        editor.config.uploadImgUrl = '/BoxApi/Kindeditor/upload';
                        // editor.config.pasteFilter = false;
                         editor.create();
                        
                })
            },
            // app.kindeditor = function(name) {
            //     app.getScript(app.params.res_url + "Js/plug/kindeditor-4.1.10/kindeditor-min.js", function() {
            //         var items = ['undo', 'redo', 'justifyleft', 'justifycenter', 'justifyright', 'fontname', 'fontsize', '|', 'forecolor', 'bold', 'underline', 'lineheight', 'removeformat', '|', 'image', 'link', 'unlink'];
            //         if (view_type == "AdminWeb") {
            //             var items = ['undo', 'redo', 'justifyleft', 'justifycenter', 'justifyright', 'fontname', 'fontsize', '|', 'forecolor', 'bold', 'underline', 'lineheight', 'removeformat', '|', 'image', 'multiimage', 'link', 'unlink', '|', 'media', 'source', 'wordpaste', 'insertfile', 'baidumap'];
            //         }
            //         if (view_type == "Wap" || view_type == "App") {
            //             var items = [];
            //         }
            //         app.showIndicator();
            //         var editor = KindEditor.create(name, {
            //             resizeType: 1,
            //             basePath: app.params.res_url + "Js/plug/kindeditor-4.1.10/",
            //             //allowPreviewEmoticons : false,
            //             //allowImageUpload : true,
            //             items: items,
            //             width: $(name).attr('w'),
            //             height: $(name).attr('h'),
            //             showRemote: false,
            //             newlineTag: "br",
            //             filterMode: false,
            //             uploadJson: '/BoxApi/Kindeditor/uploadJson',
            //             urlType: 'absolute',
            //             afterBlur: function() {
            //                 this.sync();
            //             },
            //             afterCreate: function() {
            //                 $(".ke-container").css("width", $(name).attr('w'));
            //             },
            //         });
            //         //alert(1);
            //         //alert($(name).parent().find(".ke-container").length);
            //         app.hideIndicator();
            //         $(name).bind('kindeditorChange', function() {
            //             var html = $(name).val();
            //             KindEditor.html(name, html);
            //         })
            //     });

            // },

            //ajax删除之类的操作
            app.ajaxGet = function(_this) {
                var is_confirm = $(_this).attr("confirm");
                var title = $(_this).attr("title");
                //alert( $(_this).attr("href"));

                function doAjaxGet(_this) {
                    app.showIndicator();
                    var url = $(_this).attr("href");
                    //  alert(url);
                    $.get(url, app.params.urlArgs, function(data) {
                        app.hideIndicator();
                        $(_this).trigger("ajaxGetSuccess", [data]);
                    });
                }

                if (is_confirm == 1) {
                    app.confirm(title, function() {
                        doAjaxGet(_this);
                    });
                } else {
                    doAjaxGet(_this);
                }
            },
            //登录
            app.login = function(title) {
                var title = title ? title : "";
                // var title = "";
                // if ($(window).width() > 600) {
                //     var w = 460;
                // } else {
                //     //var w="0.8";
                // }
                var user_info = app_init_data.user_info;
                if (user_info) {
                    return true;
                }
                app.modal(base_url + "/BoxLogin/Login/index", "app_login", title);
                return false;
            },

            //下拉框
            app.combox = function(_this) {
                if ($(_this).attr("target") && ($(_this).attr("target") != "")) {
                    var url = $(_this).attr("refUrl").replace(/{value}/, $(_this).val());
                    if ($(_this).attr('valuefrom') && ($(_this).attr('valuefrom') != "")) {
                        var t = $(_this).attr('valuefrom').split("|");
                        for (i = 0; i < t.length; i++)
                            url = url.replace(eval("/{" + t[i] + "}/gi"), $('#' + t[i]).val());
                    }
                    $.get(url, app.params.urlArgs, function(content) {
                        var target = $(_this).attr("target");
                        $("#" + target).html(content);
                        if ($(_this).attr("callback") && $(_this).attr("callback") != "") eval($(_this).attr("callback"))($(_this));
                    })
                }
            },


            //提示框之类的
            app.popover = function(obj) {
                var obj = $(obj);
                //alert(123);
                var content = $(obj).next().html();
                var addClass = $(obj).next().attr("addClass");
                var style = $(obj).next().attr("style");
                var add_style = {};
                if (style) {
                    style = style.split(";");
                    $.each(style, function(i, v) {
                        if (v) {
                            v = v.split(":");
                            add_style[v[0]] = v[1];
                        }
                    });
                }
                if (obj.parent().find(".popover").length > 0) {
                    event.stopPropagation();
                    return;
                }
                var options = {
                    'content': content,
                    'placement': 'bottom',
                    //'trigger':'click',
                    'html': true,
                    'title': "",
                };
                obj.popover(options);
                obj.popover("show");
                obj.next().addClass(addClass);
                var width = ($(obj).outerWidth(true)) / 2;
                var left = -Number(obj.next().css("left").replace("px", "")) + width;
                $.each(add_style, function(k, v) {
                    $(obj).next().css(k, v);
                });
                $(obj).next().find(".arrow").css("left", left);
                app.bind($(obj).next());
                $("body").find(".popover").bind(hiApp.device.click, function(event) {
                    event.stopPropagation();
                });
                if ($(obj).hasClass("popover_hover")) {
                    $(obj).parent().hover(function() {}, function() {
                        $(obj).next(".popover").remove();
                    })
                }
                event.stopPropagation();

            },
            /********确认框***/
            app.confirm = function(obj, y, n) {
                if (typeof(obj) == "string") {
                    var content = obj;
                } else {
                    var content = $(obj).attr("content");
                }
                $("#myModal_alert").find(".myModal_alert_content").html(content);
                var yes = $("#myModal_alert").find("#alert_yes");
                var no = $("#myModal_alert").find("#alert_no");
                $("#myModal_alert").modal("show");
                var type = $(obj).attr("type");
                if (typeof(obj) == "string") {
                    if (typeof(y) == "function") {
                        yes.unbind(app.device.click).bind(app.device.click, function(event) {
                            y();
                        })
                    }
                    if (typeof(n) == "function") {
                        no.unbind(app.device.click).bind(app.device.click, function(event) {
                            n();
                        });
                    }
                } else {
                    yes.unbind(app.device.click);
                    yes.attr("href", $(obj).attr("href"));
                    yes.attr("data-type", $(obj).attr("type"));
                    var callback = $(obj).attr("callback");
                    if (callback) {
                        yes.attr("onclick", callback);
                    }
                    app.bind($(obj));
                }
                return false;
            },

            //表单提交
            app.ajaxSubmit = function(obj) {
                //console.log(hiApp.params)
                app.getScript(app.params.res_url + "Js/plug/jquery.form.js", function() {
                    var _this = $(obj);
                    var novalidate = $(obj).attr('novalidate');
                    if (novalidate == "novalidate") {
                        $(obj).data('bootstrapValidator').resetForm();
                        $(obj).data('bootstrapValidator').validate();
                        var bool = $(obj).data('bootstrapValidator').isValid();
                        if (!bool) {
                            var invalidFields = $(obj).data('bootstrapValidator').getInvalidFields();
                            $(invalidFields[0]).focus();
                            return false;
                        }
                    }
                    var showRequest = $(obj).attr("showRequest") ? $(obj).attr("showRequest") : app.showRequest;
                    var showResponse = $(obj).attr("showResponse") ? $(obj).attr("showResponse") : app.showResponse;
                    if ($(obj).parents(".modal").length > 0) {
                        app.variable.modal_id = $(obj).parents(".modal").attr("id");
                    }

                    //  var target=$(obj).attr("target")?$(obj).attr("target"):"#modal_popup .modal-body";
                    var options = {
                        //  target: $(target),          //把服务器返回的内容放入id为output的元素中
                        beforeSubmit: showRequest,
                        //提交前的回调函数
                        success: function(content) {
                            showResponse(content, _this);
                        },
                        //提交后的回调函数
                        //url: post_url,                 //默认是form的action， 如果申明，则会覆盖
                        // type: "post",               //默认是form的method（get or post），如果申明，则会覆盖  值
                    };
                    if ($(obj).find('[type="submit"]').length > 0) {
                        $(obj).find('[type="submit"]').attr("disabled", "disabled");
                    }
                    $(obj).ajaxSubmit(options);
                    return false;
                })
            },

            app.showResponse = function(content, _this) {
                app.hideIndicator();
                if ($(_this).find('[type="submit"]').length > 0) {
                    $(_this).find('[type="submit"]').removeAttr("disabled");
                }
                if (content.indexOf('obj-') === 0) {
                    var content = content.slice(4);
                    var obj = JSON.parse(content);
                    if (obj.msg) {
                        dialog(obj.msg);
                    }
                    content = obj.content;
                }

                if (typeof(content) == "string" && content.indexOf("http") == 0) {
                    // app.jump(content);
                    if (_this.attr('jump')) {
                        app.jump(content);
                    } else {
                        app.modal(content);
                    }

                } else {
                    _this.trigger("ajaxSubmitSuccess", [content]);
                }



            },

            app.ajaxContent = function(_this) {
                var a = $(_this).find("a");
                $.each(a, function(i, obj) {
                    var href = $(obj).attr('href');
                    if (typeof($(obj).attr("data-type")) == "undefined" && typeof(href) == "string" && href.indexOf("/") > -1) {
                        $(obj).unbind(app.device.click).bind(app.device.click, function() {
                            app.modal(this);
                            return false;
                        });
                    }
                });

                $(_this).find("form").not("[ajax='false']").unbind("submit").bind("submit", function() {
                    app.ajaxSubmit(this);
                    return false;
                });
            },

            app.showRequest = function() {
                app.showIndicator()
            },
            //弹出
            app.popup = function(url, modal_id, h) {
                app.showIndicator();
                if (typeof(modal_id) != "string") {
                    var id = "_popup";
                } else {
                    var id = modal_id;
                }
                if (url.indexOf("http") === 0 || url.indexOf("/") === 0) {
                    var href = url;
                    var content = "";
                } else if (url.indexOf("#") === 0) {
                    var href = "";
                    var _modal_popup = $(url);
                    //设置高度
                    if (h) {
                        _modal_popup.height($(window).height() * h);
                    }
                    app.show_popup(_modal_popup);
                    return;

                } else {
                    var href = "";
                    var content = url;
                }
                //获得url
                if ($("#" + id).length > 0) {
                    var _modal_popup = $("#" + id);
                } else {
                    var html = '<div class="popup" id="' + id + '"></div>';
                    $("body").append(html);
                    var _modal_popup = $("#" + id);

                }
                //设置高度
                if (h) {
                    _modal_popup.height($(window).height() * h);
                }
                if (href) {
                    var param = app.getUrl(href);
                    var _url = param['url'];
                    var _thisUrl = _modal_popup.attr("data-url");
                    _modal_popup.attr("data-url", _url);
                }
                if (content) {
                    _modal_popup.html(content);
                    app.show_popup(_modal_popup);
                    return;
                }


                //当前模态框url与加载的url相等就不用加载
                if (typeof(_thisUrl) == "string" && _thisUrl == _url) {
                    contentReload = 0;
                    app.show_popup(_modal_popup);
                    return;
                }

                //异步获得内容
                var modal_urlArgs = app.params.urlArgs;
                modal_urlArgs['requestFrom'] = "modal";
                $.ajax({
                    //async : false,
                    type: "get",
                    data: modal_urlArgs,
                    url: _url,
                    beforeSend: function() {
                        app.showIndicator();
                    },
                    success: function(respose) {
                        content = respose;
                        if (respose.indexOf('obj-') === 0) {
                            var data = content.slice(4);
                            var obj = JSON.parse(data);
                            if (obj.msg) dialog(obj.msg);
                            content = obj.content;
                        }
                        //缓存结束
                        if (content) {
                            _modal_popup.html(content);
                        }
                        app.show_popup(_modal_popup);
                    }
                });

            },
            app.show_popup = function(_this) {
                if ($("body").find(".popupBg").length > 0) {
                    $("body").find(".popupBg").remove();
                }
                $('<div class="popupBg"></div>').insertBefore(_this);
                $(_this).addClass("popup-modal-in");
                $(".popupBg").bind(app.device.click, function() {
                    app.hide_popup();
                });
                $(_this).find(".colse").bind(app.device.click, function() {
                    app.hide_popup();
                });
                app.bind(_this);
                app.hideIndicator();
            },
            app.hide_popup = function() {
                $(".popup").removeClass("popup-modal-in");
                $("body").find(".popupBg").remove();
            },
            //加载模态框
            app.modal = function(obj, modal_id, title, w, noColse) {
                app.showIndicator();

                if (typeof(modal_id) != "string") {
                    var id = "modal_popup";
                } else {
                    var id = modal_id;
                }
                if (typeof(obj) != "string") {
                    if ($(obj).parents(".modal").length > 0) {
                        id = $(obj).parents(".modal").attr("id");
                    }

                    if ($(obj).attr('w')) {
                        w = $(obj).attr('w');
                    }

                    if ($(obj).attr('target')) {
                        id += "_" + $(obj).attr('target');
                    }
                    if (typeof(title) != "string") {
                        title = $(obj).attr('title');
                    }
                }

                if (typeof(w) == "string" && w.indexOf(".") != -1) {
                    w = $(window).width() * w;
                }

                if (app.params.ajaxLinks) {
                    if ($(".page").length == 1) {
                        add_to_page = $(".page");
                    }
                    if ($(".page-on-center").length > 0) {
                        add_to_page = $(".page-on-center");
                    }
                } else {
                    add_to_page = $("body");
                }

                var modalHead = "";
                var modal_popup_html = '<div class="modal modal_popup" id="' + id + '" >';
                modal_popup_html += '<div class="modal-dialog">';
                modal_popup_html += '<div class="modal-content" >';
                //modal_popup_html += modalHead;
                modal_popup_html += '<div class="modal-body" >';
                modal_popup_html += '</div>';
                modal_popup_html += '</div>';
                modal_popup_html += '</div>';
                modal_popup_html += '</div>';
                if ($("#" + id).length == 0) {
                    add_to_page.append(modal_popup_html);
                } else {
                    if ($(add_to_page).find("#" + id).length == 0) {
                        var clone_modal = $("#" + id).clone();
                        $("#" + id).remove();
                        $(clone_modal).appendTo($(add_to_page));
                    }
                }
                $("#" + id).find(".modal-header").remove();
                if (typeof(title) == "string" && title != "") {
                    modalHead = '<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title">' + title + '</h4></div>';
                    $(modalHead).insertBefore($("#" + id).find(".modal-body"))
                }

                var _modal_popup = $("#" + id);
                var title = "";
                if (typeof(obj) == "string" && obj.indexOf("http") == 0) {
                    var href = obj;
                } else if (typeof(obj) == "string") {
                    var content = obj;
                    //_modal_popup.find(".modal-title").html(title);
                    _modal_popup.find(".modal-body").html(content);
                    app.show_modal(_modal_popup, noColse, add_to_page);
                    return;
                } else {
                    var href = $(obj).attr("href");
                    title = $(obj).attr("title");
                }

                if (w == 1) { //新页面打开
                    app.jump(href);
                    return false;
                }
                //获得url
                param = app.getUrl(href);
                var _url = param['url'];
                var contentReload = 1;
                var _thisUrl = _modal_popup.attr("data-url");
                _modal_popup.attr("data-url", _url);
                /****宽度***/
                if (w) {
                    $(_modal_popup).find(".modal-dialog").width(w);
                }
                //当前模态框url与加载的url相等就不用加载
                if (typeof(_thisUrl) == "string" && _thisUrl == _url) {
                    contentReload = 0;
                    app.show_modal(_modal_popup, noColse, add_to_page);
                    return;
                }


                //加载过的url
                var url_key = base64_encode(_url);
                var CacheData = app.getVisCache(url_key);
                if (CacheData) {
                    content = CacheData.content;
                    contentReload = 0;
                    _modal_popup.find(".modal-body").html(content);
                    app.show_modal(_modal_popup, noColse, add_to_page);
                    return;
                }
                //异步获得内容
                var modal_urlArgs = app.params.urlArgs;
                modal_urlArgs['requestFrom'] = "modal";
                if (contentReload == 1) {
                    $.ajax({
                        //async : false,
                        type: "get",
                        data: modal_urlArgs,
                        url: _url,
                        beforeSend: function() {
                            app.showIndicator();
                        },
                        success: function(respose) {
                            content = respose;
                            if (respose.indexOf('obj-') === 0) {
                                var data = content.slice(4);
                                var obj = JSON.parse(data);
                                if (obj.msg) dialog(obj.msg);
                                content = obj.content;
                            }
                            //缓存到内存
                            if (content) {
                                var url_key = base64_encode(_url);
                                var cache_data = {
                                    url: url_key,
                                    content: content,
                                };
                                if (0) {
                                    app.addVisCache(cache_data);
                                }
                            }
                            //缓存结束
                            if (content) {
                                _modal_popup.find(".modal-body").html(content);
                            }
                            if (typeof(content) == "string" && content.indexOf("http") == 0) {
                                app.jump(content);
                                return;
                            }

                            app.show_modal(_modal_popup, noColse, add_to_page);
                        }
                    });
                }

            },
            app.show_modal = function(_modal_popup, noColse, add_to_page) {
                if (app.params.ajaxLinks) { //ajax移动端
                    //关闭时
                    _modal_popup.on('hide.bs.modal', function(e) {
                        //显示底部菜单
                        var modal = $(".toolbar").attr("modal");
                        if (modal == 1) {
                            $(".toolbar").show();
                            $(".toolbar").attr("modal", "0");
                        }
                        $("body").find('.modal-backdrop').remove();
                        $(add_to_page).find('.modal-backdrop').remove();
                        $(add_to_page).find(".page-content").removeClass("modal-open");

                    });
                    //打开时
                    _modal_popup.on('shown.bs.modal', function(e) {
                        //关闭菜单
                        if ($(".toolbar").is(":visible")) {
                            $(".toolbar").attr("modal", "1");
                            $(".toolbar").hide();
                        }
                        //
                        $("body").find('.modal-backdrop').remove();
                        if ($(add_to_page).find(".modal-backdrop").length == 0) {
                            $(add_to_page).append('<div class="modal-backdrop in"></div>');
                        }

                        $(add_to_page).find(".page-content").addClass("modal-open");

                    });
                } else {
                    if ($("body").find('.modal-backdrop').length > 0) {
                        $("body").find('.modal-backdrop').eq(0).remove();
                    }

                    _modal_popup.on('hide.bs.modal', function(e) {
                        if ($(_modal_popup).attr('backdrop') == 2) {
                            $("body").find('.modal-backdrop:last').remove();
                        }
                    });
                    _modal_popup.on('shown.bs.modal', function(e) {
                        $("body").find('.modal-backdrop').eq(1).remove();
                    })
                }

                var url = $(_modal_popup).attr("data-url");

                //alert(_modal_popup.html();)
                if (view_type == "AdminWeb") { //不能点击那个backdrop关闭
                    _modal_popup.modal({
                        backdrop: false,
                    });
                    $("body").append('<div class="modal-backdrop in"></div>');
                    var close_but = '<button type="button" class="close modal-colse" data-dismiss="modal"><span aria-hidden="true" class="">×</span><span class="sr-only">Close</span></button>';
                    $(_modal_popup).attr("backdrop", "2");
                    if ($(_modal_popup).find('[data-dismiss="modal"]').length == 0) {
                        $(close_but).prependTo($(_modal_popup).find(".modal-body"));
                    }
                }
                if (noColse == 1) { //不能关闭
                    _modal_popup.modal({
                        backdrop: false,
                    });
                    _modal_popup.find('[data-dismiss="modal"]').remove();
                }



                if (_modal_popup.attr('bind') != 1) {
                    app.set_modal_postion(_modal_popup); //定位
                    app.bind(_modal_popup);
                    var query = getQuery(url);
                    var data_page = _modal_popup.find(".page").attr("data-page");
                    if (data_page) {
                        app.cmd("init", {
                            query: query,
                            name: data_page
                        });
                    }
                }
                // alert(1);
                app.ajaxContent(_modal_popup);
                _modal_popup.modal("show");
                _modal_popup.attr("bind", 1);
                app.hideIndicator();
                _modal_popup.trigger("modalLoadSuccess");


            },


            app.set_modal_postion = function(_this) {
                // if($(".modal_popup:visible").length>0){
                //                           $(_this).css("top",0);
                //                                  return false;
                //                          }

                _this.css("top", 0);
                //打开时
                _this.on('shown.bs.modal', function(e) {

                    if ($(".modal_popup:visible").length > 1) {
                        $(_this).css("top", 0);
                        return false;
                    }
                    var h = $(_this).find('.modal-dialog').outerHeight();
                    if ($(_this).find('.page').length > 0) {
                        var h = $(_this).find('.page').find(".page-content").outerHeight() + 80;
                    }
                    //有头部
                    if ($(_this).find(".modal-header").length > 0) {
                        h += 70;
                    }
                    //  alert(h);
                    var w_h = $(window).height();
                    var l_h = w_h - h - 80;

                    //alert(l_h);
                    if (l_h > 0) {
                        var top = l_h / 2;
                        $(_this).css("top", top);
                    } else {
                        $(_this).css("top", 0);
                    }
                })

            },
            /*****禁用选中文字***/
            app.disableSelect = function() { /****禁用选中文字 **/
                if (document.all) {
                    document.onselectstart = function() {
                        return false;
                    }; //for ie
                } else {
                    document.onmousedown = function() {
                        return false;
                    };
                    document.onmouseup = function() {
                        return true;
                    };
                }
                document.onselectstart = new Function('event.returnValue=false;');
            },


           
            /***滑动标签页***/
            app.swiperPage = function(container, params) {

                var swiperContainer = container + " .swiperContent";
                var tabs = new Array();
                var swiperHtml = '<div class="swiper-wrapper">';
                //console.log("swiperPage");
                //标签页数
                var tab = $(container).find(".swiperTap li");
                var tabPane = $(container).find(".swiperContent .tabPane"); //标签页内容]
                tabPaneContent = "";
                if ($(tabPane).length == 1) {
                    tabPaneContent = tabPane.eq(0).html();
                }
                $.each(tab, function(i, v) {
                    $(v).attr("index", i);
                    var add_class = "";
                    var curPaneContent = "";
                    if ($(v).hasClass('active') && $(tabPane).length == 1) {
                        add_class = "swiper-slide-active";
                        curPaneContent = tabPaneContent;
                    } else if ($(tabPane).length > 1) {
                        curPaneContent = tabPane.eq(i).html();
                    }
                    $(v).find(".swiperTapLine").remove();
                    $(v).append('<div class="swiperTapLine" ></div>');
                    swiperHtml += '<div class="swiper-slide ' + add_class + '"> ' + curPaneContent + ' </div>';
                });
                swiperHtml += " </div>";

                if ($(container).find(".swiperContent .swiper-slide").length == 0) {
                    $(swiperContainer).html(swiperHtml); //标签页html
                }

                //alert(swiperHtml);
                app.bind($(swiperContainer));
                var h = $(container).attr("h");
                //alert(h);
                if (h > 0) {
                    $(container).find(".swiper-slide").css({
                        'height': h + 'px',
                        'overflow-y': 'scroll',
                        '-webkit-overflow-scrolling': 'touch'
                    });
                    $(container).parents(".page-content").css({ "overflow-y": "hidden" });
                }
                app.params.swiper[container] = new Swiper(swiperContainer, { //实例化
                    //autoHeight: true, //enable auto height
                    pareanContainer: container,
                    after_slideTo: function(swiper) {
                        //console.log(swiper);
                        //var swiper=app.params.swiper[container];
                        //  var container=
                        var container = $(swiper.container).parent();
                        container.trigger("swiperSlide", swiper);
                        var activeIndex = swiper.activeIndex;
                        $(container).find(".swiperTap li").removeClass("active");
                        $(container).find(".swiperTap").find("[index='" + activeIndex + "']").addClass("active");
                        app.swiperShow(swiper.params.pareanContainer, swiper);
                    },
                    onTouchMove: function(swiper, e) {
                        var container = $(swiper.container).parent();
                        var activeIndex = swiper.activeIndex;
                        var transform = $(container).find(".swiper-wrapper").css('transform');
                        var transforms = transform.split(",");
                        var w = swiper.width;
                        var li_w = $(container).find(".swiperTap").find("[index='" + activeIndex + "']").width();
                        var transform_x = ((-transforms[4] - activeIndex * w) / w) * li_w;

                        $(container).find(".swiperTap").find("[index='" + activeIndex + "'] .swiperTapLine").css("transform", "matrix(1, 0, 0, 1, " + transform_x + ", 0)");
                        container.trigger("onTouchMove", swiper);
                    },
                    onTouchEnd: function(swiper, e) {
                        var activeIndex = swiper.activeIndex;
                        $(container).find(".swiperTap").find("[index='" + activeIndex + "'] .swiperTapLine").css("transform", "matrix(1, 0, 0, 1, 0, 0)");
                        console.log('onTouchEnd');
                    }

                });

                var activeIndex = $(container).find(".swiperTap .active").attr("index");
                if (activeIndex > 0) {
                    app.params.swiper[container].slideTo(activeIndex);
                }
                $(container).trigger("swiperSlideInit", app.params.swiper[container]);
                //标签页点击
                $(tab).find("a").unbind(app.device.click).bind(app.device.click, function() {
                    var index = $(this).parent().attr("index");
                    //alert(index);
                    var swiper = app.params.swiper[container];
                    swiper.slideTo(index);
                    return false;
                });
                /*****滚动时，标签导航***/
                //      var swiperTap=$(container).find(".swiperTap");
                //                   var tabTop=swiperTap.offset().top;
                //                  $(container).parents(".page-content").scroll(function(){
                //                     var scrollTop=$(this).scrollTop();
                //                              if(scrollTop>tabTop){ 
                //                             swiperTap.addClass("swiperTapFix");
                //                              }else{
                //                                   swiperTap.removeClass("swiperTapFix");
                //                              }
                //                  })  
            },
            //滑动标签页显示
            app.swiperShow = function(container, swiper) {
                var activeIndex = swiper.activeIndex;
                var url = $(container).find(".swiperTap").find("[index='" + activeIndex + "'] a").attr("href");
                var tabPaneConent = $(container).find(".swiperContent .swiper-slide").eq(activeIndex).text();
                if (trim(tabPaneConent, " ") == "" && typeof(url) == "string" && url.indexOf("/") > -1) {
                    app.showIndicator();
                    $.get(base_url + url, app.params.urlArgs, function(content) {
                        var swiperDiv = $(container).find(".swiper-slide").eq(activeIndex);
                        var html = $(content).find(container).find(".tabPane:eq(0)").html();
                        swiperDiv.html(html);
                        app.bind(swiperDiv);
                        app.hideIndicator();
                        $(container).trigger("swiperSlideInitPage", swiper);
                    })

                }

            },
 /*******播放视频监听***/
            app.videoLoadedHandler = function(id, s) {
                if (id) {
                    var play_id = "ckplayer_" + id;
                    var _this = $("#" + id);
                    var video = CKobject.getObjectById(play_id);
                    if (video.getType()) { //说明使用html5播放器
                        video.addListener('play', _this.trigger("videoPlay", [s]));
                        //video.addListener('play',playHandler(play_id,s));
                        video.addListener('pause', _this.trigger("videoPause"));
                        //  video.addListener('time',_this.trigger("videoTime"));
                        var curl_video = $("#" + play_id)[0];
                        curl_video.ontimeupdate = function() {
                            //timeHandler(play_id);
                            _this.trigger("videoTime");
                        };
                    } else {
                        video.addListener('play', _this.trigger("videoPlay", [s]));
                        video.addListener('pause', _this.trigger("videoPause"));
                        video.addListener('time', _this.trigger("videoTime"));

                    }
                }

            },
            /*******播放视频***/
            app.playVideoWap = function(param) {
                app.getScript(app.params.res_url + "Js/plug/ckplayer6.6/ckplayer/ckplayer.js", function() {
                    var url = param['url'];
                    var id = "#" + param['id'];
                    var flashvars = {
                        f: url,
                        c: 0,
                        p: 2,
                        b: 0,
                        h: 1,
                        e: 0,
                        i: param['image'],
                        //subtitle_en:param['subtitle_en'],
                       loaded: "hiApp.videoLoadedHandler('" + param['id'] + "')",
                    };
                    $.each(param, function(i, v) {
                        flashvars[i] = v;
                    });


                    if (param['subtitle_html5']) {
                        flashvars['subtitle_html5'] = param['subtitle_html5'];
                    }


                    //console.log(flashvars);
                    var params = {
                        bgcolor: '#FFF',
                        allowFullScreen: false,
                        allowScriptAccess: 'always',
                        wmode: 'transparent'
                    };

                    var h = $("#" + param['id']).height();
                    var w = $("#" + param['id']).width();
                    var params = { bgcolor: '#FFF', allowFullScreen: true, allowScriptAccess: 'always', wmode: 'transparent' };
                    var video = [url + '->video/mp4'];
                    CKobject.embed(app.params.res_url + 'Js/plug/ckplayer6.6/ckplayer/ckplayer.swf', param['id'], "ckplayer_" + param['id'], w, h, true, flashvars, video, params);

                })
            },

            app.playVideoWeb=function(param){
                 app.getScript("http://cdn.aodianyun.com/lss/ckplayer/player.js", function() {
                      var h = $("#" + param['id']).height();
                    var w = $("#" + param['id']).width();
                      var flashvars={f:'http://cdn.aodianyun.com/lss/ckplayer/m3u8.swf',a:param['url'],c:0,s:4,i:param['image'],lv:0, loaded: "hiApp.videoLoadedHandler('" + param['id'] + "')"};
                      var params={bgcolor:'#FFF',allowFullScreen:true,allowScriptAccess:'always',wmode:'transparent'};
                      var video=[param['url']];
                      CKobject.embed('http://cdn.aodianyun.com/lss/ckplayer/ckplayer.swf',param['id'], "ckplayer_" + param['id'],w,h,false,flashvars,video,params);
                });
            },
            
            //wap playVideo

            app.playVideo = function(param) {
                if (app.params.view_type == "Web") {
                    app.playVideoWeb(param);
                } else {
                    app.playVideoWap(param);
                }
            },





            app.getUrl = function(url) {
                var viewURL = url ? url : window.location.href;
                //console.log(viewURL)
                var query = getQuery(viewURL);
                //console.log(query)
                var root_url = viewURL;
                var origin = app.params.base_url;
                var pushStateSeparator = app.params.pushStateSeparator;
                if (viewURL.indexOf(pushStateSeparator) >= 0 && viewURL.indexOf(pushStateSeparator + '#') < 0) {
                    viewURL = viewURL.split(pushStateSeparator);
                    var l = $(viewURL).length;
                    var url = viewURL[l - 1];
                    var root_url = viewURL[0];
                    if (url == "" || url.indexOf("/") == -1) {
                        url = viewURL[0];
                    } else if (url.indexOf("http://") == -1) {
                        url = origin + url;
                    }
                } else {
                    root_url = url = viewURL;
                }
                var param = {
                    'url': url,
                    'root_url': root_url,
                    'query': query,
                };
                return param;
            },
            app.cmd = function(act_name, page) {
                //  app.getScript(app.params.controllersPath+"/controllers.js",function(act_name, page){
                if (typeof(page) != "object") return;
                var name = page.name;
                var query = page.query;
                /**app是一个数组**/
                if (typeof(appName) == "object") {
                    $.each(appName, function(i, app_one_name) {
                        //if(act_name=="init")
                        CM.run("appCtrl", act_name, page, app_one_name); //每次执行这个appCtrl
                        CM.run(name + "Ctrl", act_name, page, app_one_name);

                    });
                }
                /****app是一个字符串**/
                if (typeof(appName) == "string") {
                    CM.run("appCtrl", act_name, page, appName);
                    CM.run(name + "Ctrl", act_name, page, appName);
                }
                //  })       
            },


            /******播放mp3***/
            app.play_mp3 = function(mp3) {
                //console.log("开始");
                hiApp.showIndicator();
                loadAudio(mp3, function() {
                    if ($("#mp3div").length > 0) {
                        $("#mp3div").remove();
                    }
                    var html = "<div id='mp3div' style='display:none'>";
                    html += '<audio id="music" src="' + mp3 + '" preload="auto" controls >';
                    html += "</div>";
                    $("body").append(html);
                    audio = $("#music")[0];;
                    audio.play();
                    hiApp.hideIndicator();
                    //console.log("方向");
                });

                function loadAudio(src, callback) {
                    var audio = new Audio(src);
                    audio.onloadedmetadata = callback;
                    audio.src = src;
                }
            },
            /******alert***/
            app.alert = function(content, callback, autohide) {
                //dialog(msg);
                if (typeof(autohide) == "undefined") {
                    autohide = 2000;
                }
                $(".dialog").remove();
                $("body").append('<div class="dialog alert alert-danger"></div>');
                if (content) {
                    $(".dialog").html(content);
                    var w = "-" + $(".dialog").width() / 2 + "px";
                    $(".dialog").css({
                        "top": '70%',
                        "left": "50%",
                        "margin-left": w
                    });
                    re = setTimeout(function() {
                        $(".dialog").fadeOut(500);
                        if (typeof(callback) == "function") {
                            callback();
                        }
                    }, autohide);


                }
            },
            /*****circle,圆进度**/
            app.circle = function(_this) {
                var border = $(_this).attr("border") ? $(_this).attr("border") : "1";
                var per = $(_this).attr("per") ? $(_this).attr("per") : "0";
                var w = $(_this).attr('w');
                var h = w / 2;
                per = Number(per);
                if (per < 50 || per == 50) {
                    var right_deg = per * 3.6 + 45;
                    var left_deg = 45;
                } else {
                    var left_deg = (per - 50) * 3.6 + 45;
                    var right_deg = 225;
                }
                $(_this).find(".circleWrapper").remove();
                var html = "";
                html += '<div class="circleWrapper" style="right:0px">';
                html += '<div class="circleProgress rightcircle"></div>';
                html += '</div>';
                html += '<div class="circleWrapper" style="left:0px">';
                html += '<div class="circleProgress leftcircle"></div>';
                html += '</div>';
                $(html).prependTo($(_this));
                $(_this).css({
                    'width': w + "px",
                    "height": w + "px",
                    'border-width': "0px"
                });
                $(_this).find(".circleWrapper").css({
                    'width': h + "px",
                    "height": w + "px"
                });
                $(_this).find(".circleProgress").css({
                    'width': w + "px",
                    'height': w + "px",
                    'border-width': border + "px"
                });
                $(_this).find(".rightcircle").css({
                    'transform': 'rotate(' + right_deg + 'deg)',
                    '-ms-transform': 'rotate(' + right_deg + 'deg)',
                    /* Internet Explorer */
                    '-moz-transform': 'rotate(' + right_deg + 'deg)',
                    /* Firefox */
                    '-webkit-transform': 'rotate(' + right_deg + 'deg)',
                    /* Safari 和 Chrome */
                    '-o-transform': 'rotate(' + right_deg + 'deg)',
                    /* Opera */
                });
                $(_this).find(".leftcircle").css({
                    'transform': 'rotate(' + left_deg + 'deg)',
                    '-ms-transform': 'rotate(' + left_deg + 'deg)',
                    /* Internet Explorer */
                    '-moz-transform': 'rotate(' + left_deg + 'deg)',
                    /* Firefox */
                    '-webkit-transform': 'rotate(' + left_deg + 'deg)',
                    /* Safari 和 Chrome */
                    '-o-transform': 'rotate(' + left_deg + 'deg)',
                    /* Opera */
                })

            },
            //运行app
            app.run = function() {
                var params = app.getUrl();
                _url = params.url;
                root_url = params.root_url;
                $(document).trigger('appBeforeRun');
                var int_page = $(".page").eq(0);
                if ($(int_page).length > 0) {
                    int_page.attr("url", root_url);
                    var content = int_page.prop("outerHTML");
                    var name = int_page.attr("data-page");
                    var options = {
                        url: root_url,
                        time: (new Date()).getTime(),
                        content: content,
                        name: name,
                        query: params.query,
                    };
                    var url_key = base64_encode(root_url);
                    if (app.params.cache) {
                        var cache_data = {
                            url: url_key,
                            content: content,
                        };
                        app.addVisCache(cache_data);
                    }
                    //console.log(options);

                    $(document).trigger('pageBeforeInit', [options]);
                    if (root_url != _url) {
                        var url_param = app.getUrl(_url);
                        app.router.load(app.view, url_param);
                    }
                }
                /***初始url***/
                if (app.params.int_url) {
                    app.router.load_url(app.params.int_url);
                }

                $(document).trigger("pageAfterShow", [options]);
            },

            /************监听路由变化*****/
            $(window).bind('hashchange', function() {
                //var app_params_hashchange=$("[name='app_params_hashchange']").val();
                console.log("hashchange:" + app.params.hashchange);
                if (app.params.hashchange == 1) return;
                param = app.getUrl();
                app.router.load(app.view, param);
            });
        app.init = function() {
            $(document).on('pageBeforeInit', function(e, page) {

                var name = page.name;
                if (page.name != "undefind") {
                    if (typeof(app.variable[name]) == "undefind") {
                        app.variable[name] = {};
                    }
                    app.cmd('init', page);
                    if (app.firstInit == 1 && app.params.appInt) {
                        app.params.appInt();
                        app.firstInit = 0;
                    }
                }
            });

            $(document).on('pageBeforeShow', function(e, page) {
                app.cmd('beforeShow', page);
            });


            // $(document).on('pageAfterShow', function(e, page) {
            //     app.cmd('afterShow', page);
            // });

            $(document).on('pageAfterHide', function(e, page) {
                app.cmd('afterHide', page);
            });

            $(document).on('pageAfterShow', function(e, page) {
                if (typeof(page) != "object") return;
                app.bindAfterShow($("[data-page='" + page.name + "']"));
                app.cmd('afterShow', page);
                //CM.run('appCtrl',)
            });


            app.bind("");
            /****禁用选文字***/

            if (app.params.disableSelect) {
                app.disableSelect();
            }
            $(document).on('appRun', function() {
                app.run();
            });
            app.hasinit = 1; //app
        }

    }

})();




$.fn.animationEnd = function(callback) {
    var events = ['webkitAnimationEnd', 'OAnimationEnd', 'MSAnimationEnd', 'animationend'],
        i, j, dom = this;

    function fireCallBack(e) {
        callback(e);
        for (i = 0; i < events.length; i++) {
            dom.off(events[i], fireCallBack);
        }
    }

    if (callback) {
        for (i = 0; i < events.length; i++) {
            dom.on(events[i], fireCallBack);
        }
    }
    return this;
};

/*===========================
 Device/OS Detection
 ===========================*/
m.prototype.device = (function() {
    var device = {};
    var ua = navigator.userAgent;
    var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
    var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
    var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
    var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);

    device.ios = device.android = device.iphone = device.ipad = device.androidChrome = false;
    device.pc = true;
    // Android
    if (android) {
        device.os = 'android';
        device.osVersion = android[2];
        device.android = true;
        device.androidChrome = ua.toLowerCase().indexOf('chrome') >= 0;
    }
    if (ipad || iphone || ipod) {
        device.os = 'ios';
        device.ios = true;
    }
    // iOS
    if (iphone && !ipod) {
        device.osVersion = iphone[2].replace(/_/g, '.');
        device.iphone = true;
    }
    if (ipad) {
        device.osVersion = ipad[2].replace(/_/g, '.');
        device.ipad = true;
    }
    if (ipod) {
        device.osVersion = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
        device.iphone = true;
    }
    // iOS 8+ changed UA
    if (device.ios && device.osVersion && ua.indexOf('Version/') >= 0) {
        if (device.osVersion.split('.')[0] === '10') {
            device.osVersion = ua.toLowerCase().split('version/')[1].split(' ')[0];
        }
    }

    // Webview
    device.webView = (iphone || ipad || ipod) && ua.match(/.*AppleWebKit(?!.*Safari)/i);

    // Minimal UI
    if (device.os && device.os === 'ios') {
        var osVersionArr = device.osVersion.split('.');
        device.minimalUi = !device.webView && (ipod || iphone) && (osVersionArr[0] * 1 === 7 ? osVersionArr[1] * 1 >= 1 : osVersionArr[0] * 1 > 7) && $('meta[name="viewport"]').length > 0 && $('meta[name="viewport"]').attr('content').indexOf('minimal-ui') >= 0;
    }

    // Check for status bar and fullscreen app mode
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    device.statusBar = false;
    if (device.webView && (windowWidth * windowHeight === screen.width * screen.height)) {
        device.statusBar = true;
    } else {
        device.statusBar = false;
    }

    if (device.android || device.ios || device.iphone || device.ipad) {
        device.pc = false;
    }

    if (device.pc) {
        device.click = "click";
    } else {
        device.click = "click";
    }

    // Classes
    var classNames = [];
    // Pixel Ratio
    device.pixelRatio = window.devicePixelRatio || 1;
    classNames.push('pixel-ratio-' + Math.floor(device.pixelRatio));
    if (device.pixelRatio >= 2) {
        classNames.push('retina');
    }

    // OS classes
    if (device.os) {
        classNames.push(device.os, device.os + '-' + device.osVersion.split('.')[0], device.os + '-' + device.osVersion.replace(/\./g, '-'));
        if (device.os === 'ios') {
            var major = parseInt(device.osVersion.split('.')[0], 10);
            for (var i = major - 1; i >= 6; i--) {
                classNames.push('ios-gt-' + i);
            }
        }

    }
    // Status bar classes
    if (device.statusBar) {
        classNames.push('with-statusbar-overlay');
    } else {
        $('html').removeClass('with-statusbar-overlay');
    }

    // Add html classes
    if (classNames.length > 0) $('html').addClass(classNames.join(' '));

    // Export object
    return device;
})();

/*********************全局函数***********************/

function dialog(content, callback, autohide) {
    if (typeof(autohide) == "undefined") {
        autohide = 2000;
    }
    $(".dialog").remove();
    $("body").append('<div class="dialog alert alert-danger"></div>');
    if (content) {
        $(".dialog").html(content);
        var w = "-" + $(".dialog").width() / 2 + "px";
        $(".dialog").css({
            "top": '70%',
            "left": "50%",
            "margin-left": w
        });
        re = setTimeout(function() {
            $(".dialog").fadeOut(500);
            if (typeof(callback) == "function") {
                callback();
            }
        }, autohide);


    }
}


/******加载下一页*****************/

function ajaxNextUrlPage(obj) {
    var next_input = $(obj).next("input");
    var nextUrl = $(next_input).val(); //下一页URL
    $(next_input).val(""); //下一页为空以免重复加载
    if (nextUrl == "" || typeof(nextUrl) == "undefined") {
        dialog("没有更多了！！");
        $('.ajax_loading').hide();
        $("#pullDown").hide();
        return false; //没有一下页了
    }
    hiApp.get(nextUrl, function(ret) {
        var html = $(ret).find(".after_div").html();
        var NownextUrl = $(ret).find("#nextUrl").val();
        $(obj).parent().prev(".after_div").append(html); //将ajxa请求的数据追加到内容里面
        $(next_input).val(NownextUrl);
        hiApp.bind($(obj).parent().prev(".after_div"));
    });
}


/*********加载页面*******/
function load_page(url, source, to_id, act, func) {
    if (typeof(act) == "undefined") {
        act = "append";
    }
    $.getJSON(url, app.params.urlArgs, function(data) {
        if (data.data == null) {
            return;
        }
        var html = box_render(data.data.list, source, to_id, act);
        if (data.nextUrl != "") {
            $(to_id).next(".pagerTemplate").html($("#pagerTemplate").html());
            $(to_id).next(".pagerTemplate").find("#nextUrl").val(data.nextUrl);
            $(to_id).next(".pagerTemplate").find("#nextUrl").attr("source", source);
        }
        if (typeof(func) == "function") {
            func();
        }
    })
}

/******渲染数据****/
function box_render(data, source, to_id, act) {
    var source_html = $(source).html();
    //console.log(source_html);
    Render_data = {
        'items': data
    };
    var render = template.compile(source_html);
    var compiledRendered = render(Render_data);
    if (typeof(to_id) == "undefined") {
        return compiledRendered;
    } else if ($(to_id).length > 0) {
        if (act == "append") {
            $(to_id).append(compiledRendered);
        } else if (act == "html") {
            $(to_id).html(compiledRendered);
        } else if (act == "prepend") {
            $(to_id).prepend(compiledRendered);
        }
        hiApp.bind($(to_id));
    }
}

/******获得url参数****/

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

function getQuery(viewURL) {
    if (typeof(viewURL) != "string") {
        return;
    }
    if (viewURL.indexOf("#") >= 0) {
        urls = viewURL.split("#");
        if (urls[1] != "" && urls[1].indexOf("/") >= 0) {
            url = urls[1];
        } else {
            url = viewURL;
        }
    } else {
        url = viewURL;
    }

    var param = {};
    //console.log("getQuery:"+url);
    param = GetRequest2(url);
    //console.log(param);
    if (url.indexOf("?") >= 0) {
        var params = GetRequest(url);
        $.each(params, function(i, v) {
            param[i] = v
        });
    }
    return param;
}

function GetRequest2(url) {
    url = trim(url, "/");
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.split("?");
        str = str[0];
    } else {
        str = url;
    }

    if (str.indexOf("/") != -1) {
        strs = str.split("/");
        var strs_array = new Array();
        if (url.indexOf("http://") > -1 && url.indexOf("https://")) {
            for (var i = 3; i < strs.length; i++) {
                strs_array.push(strs[i]);
            }
        } else {
            strs_array = strs;
        }
        //console.log(strs_array);
        for (var i = 0; i < strs_array.length; i++) {
            if (i % 2 == 0 && strs_array[i]) {
                theRequest[strs_array[i]] = strs_array[i + 1];
            }
        }

    }
    return theRequest;
}

function GetRequest(url) {
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.split("?");
        str = str[1];
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}
/******获得url参数结束****/

function trim(cstring, s) {
    //console.log(cstring.substring(0));
    if (cstring.substr(0, 1) == s) {
        //字符串以"开头，去掉"
        cstring = cstring.substr(1, cstring.length - 1)
    }
    if (cstring.substr(-1) == s) {
        //字符串以"结尾，去掉"
        cstring = cstring.substr(0, cstring.length - 2)
    }
    return cstring;
}

//项目初始化参数

function get_param(urlArgs) {
    var params = S('con-app_init_data');
    var async = true;
    if (!params) {
        async = false;
    }
    var data = {};
    $.ajax({
        type: "get",
        timeout: 3000,
        async: async,
        dataType: 'json',
        data: urlArgs,
        url: base_url + "/BoxApi/Index/get_init_param",
        success: function(respose) {
            params = respose;
            app_init_data = respose;
            // console.log(S('app_init_data'));
            var old_BoxVersionCache = S('con-BoxVersionCache');
            if (old_BoxVersionCache != params.params.BoxVersionCache) {
                store.clear();
            }
            S('con-app_init_data', params);
            S('con-BoxVersionCache', params.params.BoxVersionCache);

            //alert("old_BoxVersionCache"+":"+old_BoxVersionCache);
            //alert("new_BoxVersionCache"+":"+params.params.BoxVersionCache);
        }
    });
    return params;
}


//使用store.js 缓存 最大4M

function S(key, value, version) {
    if (typeof(key) == "string" && key.indexOf('con-') === 0) { //不用加版本号的缓存
        key = key.slice(4);
    } else if (typeof(version) != "undefined") {
        key = version + ":" + key;
    } else if (typeof(app_params) != "undefined" && app_params['BoxVersionCache']) {
        key = app_params['BoxVersionCache'] + ":" + key;
    }
    if (!store.enabled) {
        return false;
    }
    if (value === null) {
        store.remove(key);
    }
    if (value) {
        try {
            store.set(key, value);
        } catch (err) {
            if (err.name == 'QuotaExceededError') {
                store.clear(); //如果缓存已满则清空
            }
        }
    }
    if (typeof(value) == "undefined" || value == "") {
        return store.get(key);
    }
    if (typeof(key) == "undefined") {
        return store.getAll();
    }
    if (key == null) {
        store.clear();
    }
}

function F(key, value, expiry) {
    if (app_params.view_type == "app") {
        return fs_save(key, value);
    } else {
        //return DB_Cache(key,value,expiry);
        return null;
    }
}


function Fget(key, f1, f2) {
    if (app_params.view_type == "app") {
        fs_get(key, f1, f2);
    } else {
        f2();
        //DB_Get_Cache(key,f1,f2);
        //return null;
    }
}



//绑定事件

function bindEvents(bindings) {
    for (var i in bindings) {
        if (bindings[i].selector) {
            $(bindings[i].element).off(bindings[i].event, bindings[i].selector, bindings[i].handler);
            $(bindings[i].element).on(bindings[i].event, bindings[i].selector, bindings[i].handler);
        } else {
            //alert(bindings[i].element);
            $(bindings[i].element).unbind(bindings[i].event);
            $(bindings[i].element).bind(bindings[i].event, bindings[i].handler);
        }
    }
}

/*
 * Javascript base64_encode() base64加密函数
 用于生成字符串对应的base64加密字符串
 * 吴先成  www.51-n.com ohcc@163.com QQ:229256237
 * @param string str 原始字符串
 * @return string 加密后的base64字符串
 */
function base64_encode(str) {
    var c1, c2, c3;
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var i = 0,
        len = str.length,
        string = '';

    while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
            string += base64EncodeChars.charAt(c1 >> 2);
            string += base64EncodeChars.charAt((c1 & 0x3) << 4);
            string += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            string += base64EncodeChars.charAt(c1 >> 2);
            string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            string += base64EncodeChars.charAt((c2 & 0xF) << 2);
            string += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        string += base64EncodeChars.charAt(c1 >> 2);
        string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        string += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
        string += base64EncodeChars.charAt(c3 & 0x3F)
    }
    return string
}


/*
 * Javascript base64_decode() base64解密函数
 用于解密base64加密的字符串
 * 吴先成  www.51-n.com ohcc@163.com QQ:229256237
 * @param string str base64加密字符串
 * @return string 解密后的字符串
 */
function base64_decode(str) {
    var c1, c2, c3, c4;
    var base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
    var i = 0,
        len = str.length,
        string = '';

    while (i < len) {
        do {
            c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff]
        } while (
            i < len && c1 == -1);

        if (c1 == -1) break;

        do {
            c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff]
        } while (
            i < len && c2 == -1);

        if (c2 == -1) break;

        string += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));

        do {
            c3 = str.charCodeAt(i++) & 0xff;
            if (c3 == 61) return string;

            c3 = base64DecodeChars[c3]
        } while (
            i < len && c3 == -1);

        if (c3 == -1) break;


        string += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));

        do {
            c4 = str.charCodeAt(i++) & 0xff;
            if (c4 == 61) return string;
            c4 = base64DecodeChars[c4]
        } while (
            i < len && c4 == -1);

        if (c4 == -1) break;

        string += String.fromCharCode(((c3 & 0x03) << 6) | c4)
    }
    return string;
}

/*****************路由**********************/
var CMUrlCache = {};
(function(window) {
    var CM = {
        run: function(name, act_name, query, app_name_one) {

            var controllers_url = app_name_one + "_" + name;
            console.log(controllers_url);
            if ($.inArray(controllers_url, controllers_list) == -1) {
                return false;
            } else {
                console.log("controllers_url 没有定义：" + name);
            }
            var data_page = name.replace("Ctrl", "");
            var url = app_params.controllersPath + "/" + app_name_one + "/" + name + ".js";
            var script_id = base64_encode(url);
            if (!CMUrlCache[script_id]) {
                var loaded = JS.load(url, hiApp.params.BoxVersion);
            } else {
                var loaded = 1;
            }

            if ($("[data-page='" + data_page + "']").attr("data-" + act_name) == 1 && act_name != "afterHide" && act_name != "afterShow") {
                return false;
            }

            if ($("[data-page='" + data_page + "']").length > 0) {
                $("[data-page='" + data_page + "']").attr("data-" + act_name, "1");
            }

            if (data_page == "app") {
                if ($(".page:visible").attr("data-app") == 1 && act_name != "afterHide" && act_name != "afterShow") {
                    return false;
                }
                $(".page:visible").attr("data-app", "1");
            }
            //alert(name+act_name);

            //console.log(app_params.controllersPath + "/" + app_name_one + "/" + name + ".js" + hiApp.params.BoxVersion);
            if (loaded) {
                CMUrlCache[script_id] = 1;
                var function_name = app_name_one + "_" + name + "." + act_name;
                var act_name_type = typeof(eval(function_name));
                if (act_name_type == "function") {
                    var data = "";
                    if (typeof(query) == "object") {
                        data = {
                            'name': query.name,
                            'url': query.url,
                            'query': query.query,
                            'root_url': query.root_url
                        };
                        data = JSON.stringify(data);
                    }
                    var command = function_name + "(" + data + ")";
                    //console.log(command);
                    //alert(123);
                    eval(command);
                } else {
                    console.log(app_name_one + "项目里的" + name + "不存" + act_name + "方法");
                }
            } else {
                console.log(app_name_one + "项目里不存在" + name);
            }

        },
        init: function(app, name) {
            controllers_name = app + "_" + name;
            if ($.inArray(controllers_name, controllers_list) == -1) {
                return false;
            }
            var url = app_params.controllersPath + "/" + app + "/" + name + ".js";
            var script_id = base64_encode(url);
            if (!CMUrlCache[script_id]) {
                var loaded = JS.load(url, hiApp.params.BoxVersion);
            } else {
                var loaded = 1;
            }
            //var loaded = JS.load(app_params.controllersPath + "/" + app + "/Js/" + name + ".js", hiApp.params.BoxVersion);
            var obj = eval(controllers_name);
            return obj;
            // console.log(name);
            //console.log(  typeof(eval(name)));
        }
    };
    window.CM = CM;
})(window);

/*****************JS CSS TPL 加载**********************/
(function(window) {
    //实现js文件的缓存
    var JC = {
        HEAD: "head",
        BODY: "body",
        VERSION: "2015061915324",
        KEYPREFIX: "2092_CF_WX_",
        //加载js文件
        load: function(filePath, version, tag, params) {
            if (arguments.length == 2 && typeof(arguments[1]) == 'object') {
                params = arguments[1];
                version = null;
                tag = null;
            };
            tag = tag || JC.HEAD;
            version = version || JC.VERSION;
            //alert(version);
            var source = JC.getCacheJSData(filePath, version);
            //  console.log(source);
            //console.log("<script src='" + filePath + "?v=" + version + "'><\/script>");
            if (typeof(source) == "undefined") {
                return false;
            }
            if (source.error > 0) {
                $(tag).append("<script src='" + filePath + "?v=" + version + "'><\/script>");
                return false;
            } else {
                source = source.msg;
            }
            if (params) {
                source = source.replace('[%params%]', JSON.stringify(params));
            }
            var script = document.createElement("script");
            script.language = "javascript";
            script.type = "text/javascript";
            script.defer = false;
            script.text = source;
            var heads = document.getElementsByTagName(tag);
            if (heads.length) {
                heads[heads.length - 1].appendChild(script);
            } else {
                document.documentElement.appendChild(script);
            }
            return true;
        },
        //请求js文件
        getCacheJSData: function(filePath, version) {
            var source = null;
            var skey = base64_encode(filePath);
            if (version) { //获得版本号
                source = S(skey, "", version);
                //console.log(source);
                if (source) {
                    //console.log(filePath+"使用了缓存");
                    return source;
                }
            }
            var data = {
                //runThreadKey:url_token,
                url: filePath,
            };

            //if(filePath.indexOf("http")>-1){
            //          var url = base_url+"/BoxApi/Index/getRes";
            //          var dataType="json";
            //      }else{
            //          var url =   filePath;
            //          var dataType="text";
            //          data={};
            //      }
            var url = filePath;
            var dataType = "text";
            data = {};
            //如果没有缓存则网络请求js
            $.ajax({ //同步请求js文件
                async: false,
                cache: false,
                dataType: dataType,
                data: data,
                url: url,
                success: function(data) {
                    if (typeof(data) == "string") {
                        source = {
                            error: 0,
                            msg: data
                        };
                    } else {
                        source = data;
                    }
                }
            });
            //console.log(source);
            if (version) {
                S(skey, source, version);
            }
            return source;
        }
    };

    window.JS = JC;
    var CSS = {
        HEAD: "head",
        BODY: "body",
        VERSION: "2015061915324",
        KEYPREFIX: "2092_CF_WX_",
        //加载js文件
        load: function(filePath, version, tag, params) {

            if (arguments.length == 2 && typeof(arguments[1]) == 'object') {
                params = arguments[1];
                version = null;
                tag = null;
            };

            tag = tag || JS.HEAD;
            version = version || JS.VERSION;
            var source = JS.getCacheJSData(filePath, version);
            if (typeof(source == "undefined")) {
                console.log(filePath + "不存在！");
                return;
            }
            if (source.error > 0) {
                document.write('<link rel="stylesheet" href="' + filePath + '?v=' + version + '" type="text/css">');
                return false;
            }
            source = source.msg;
            if (params) {
                source = source.replace('[%params%]', JSON.stringify(params));
            }

            var script = "<style>" + source + "</style>";
            $(tag).append(script);
            return true;
        }
    };
    window.CSS = CSS;

    var TPL = {
        HEAD: "body",
        BODY: "body",
        VERSION: "2015061915324",
        KEYPREFIX: "2092_CF_WX_",
        //加载js文件
        load: function(filePath, version, tag, params) {
            if (arguments.length == 2 && typeof(arguments[1]) == 'object') {
                params = arguments[1];
                version = null;
                tag = null;
            };
            tag = tag || TPL.HEAD;
            version = version || JS.VERSION;
            var source = JS.getCacheJSData(filePath, version);

            if (source.error > 0) {
                return false;
            }
            source = source.msg;
            if (params) {
                source = source.replace('[%params%]', JSON.stringify(params));
            }
            //console.log(tag);
            $(tag).append(source);
            return true;
        }
    };
    window.TPL = TPL;


})(window);
